<?php
namespace app\base\controller;

use think\Db;
use think\Image;

class Ajax extends BaseCtrl
{
    /**
     * 通用删除
     */
    public function remove()
    {
        $where = $this->post['where'];
        if (!is_array($where)) {
            $where = ['id' => $where];
        }
        $result = Db::table($this->post['tn'])->where($where)->delete();
        if ($result) {
            $this->returnAPI('删除成功', 0);
        }
        $this->returnAPI('删除失败,请稍后重试');
    }
    /**
     * 通用更新
     */
    public function update()
    {
        $where = $this->post['where'];
        if (!is_array($where)) {
            $where = ['id' => $where];
        }
        $result = Db::table($this->post['tn'])->where($where)->update($this->post['update']);
        if ($result) {
            $this->returnAPI('操作成功', 0);
        }
        $this->returnAPI('操作失败,请稍后重试');
    }
    /**
     * 通用上传
     */
    public function upload()
    {
        $path = isset($this->post['path']) ? $this->post['path'] : 'images';
        $file = $this->request->file(isset($this->post['name']) ? $this->post['name'] : 'file');
        if ($file) {
            $move = ROOT_PATH . 'public' . DS . 'upload' . DS . $path;
            $info = $file->rule('md5')->move($move);
            if ($info) {
                $src      = $move . DS . $info->getSaveName();
                $if_image = getimagesize($src);
                if ($if_image !== false) {
                    $thumb = str_replace('.', '_thumb.', $src);
                    $image = Image::open($src);
                    $image->thumb(150, 150)->save($thumb);
                }
                $return = ['src' => str_replace('\\', '/', str_replace(ROOT_PATH . 'public', $this->host, $src))];
                if (isset($thumb)) {
                    $return['thumb'] = str_replace('\\', '/', str_replace(ROOT_PATH . 'public', $this->host, $thumb));
                }
                $this->returnAPI('上传成功', 0, $return);
            }
            $this->returnAPI($file->getError());
        }
        $this->returnAPI('上传失败,请稍后重试');
    }
}
